<template>
  <div>
    <!-- 表格 -->
    <el-table :data="adminData" style="width: 80%;margin: 0 auto;" v-if="tableShow">
      <el-table-column prop="id" label="id" align="center"></el-table-column>
      <el-table-column prop="name" label="名称" align="center"></el-table-column>
      <el-table-column prop="mail" label="邮箱" align="center"></el-table-column>
      <el-table-column prop="super" label="超级管理员" align="center">
        <template #default="scope">
          <span>{{ scope.row.super ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" align="center">
        <template #default="scope">
          <el-tooltip effect="dark" placement="bottom" content="编辑">
            <el-button type="primary" :icon="Edit" circle
              :disabled="loginAdminData.super ? false : (scope.row.id == loginAdminData.id ? false : true)"
              @click="currentDataChange(scope.row, currentAdminData); dialogShowStatus.editAdmin = true;" />
          </el-tooltip>
          <el-tooltip effect="dark" placement="bottom" content="删除">
            <el-button type="danger" :icon="Delete" circle
              :disabled="loginAdminData.super ? false : (scope.row.id == loginAdminData.id ? false : true)"
              @click="currentDataChange(scope.row, currentAdminData); deleteAdmin()" />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <h1 style="font-size: 3rem;text-align: center;" v-else>数据正在加载...</h1>
    <el-button id="addAdmin" @click="dialogShowStatus.addAdmin = true">添加管理员</el-button>
    <!-- 添加管理员对话框 -->
    <el-dialog v-model="dialogShowStatus.addAdmin" title="添加管理员">
      <el-form ref="addAdminFormRef" :rules="formRuleAddAdmin" :model="adminAddData" label-position="top">
        <el-form-item label="管理员名称" prop="name">
          <el-input v-model="adminAddData.name" placeholder="请输入管理员名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="mail">
          <el-input v-model="adminAddData.mail" placeholder="请输入管理员邮箱" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="adminAddData.password" placeholder="请输入密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="passwordAgain">
          <el-input v-model="adminAddData.passwordAgain" placeholder="请再次输入密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="超级管理员权限(确定后无法修改)">
          <span style="margin-right: 1rem;">{{ adminAddData.super ? '开启' : '关闭' }}</span>
          <el-switch v-model="adminAddData.super" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogShowStatus.addAdmin = false">取消</el-button>
          <el-button type="primary" @click="addAdmin(); dialogShowStatus.addAdmin = false;">提交</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 编辑管理员对话框 -->
    <el-dialog v-model="dialogShowStatus.editAdmin" title="编辑管理员">
      <el-form ref="editAdminFormRef" :model="currentAdminData" label-position="top" :rules="formRuleEditAdmin">
        <el-form-item prop="id">
          <span>{{ 'id：' + currentAdminData.id }}</span>
        </el-form-item>
        <el-form-item label="管理员名称" prop="name">
          <el-input v-model="currentAdminData.name" placeholder="请输入管理员名称" clear></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="mail">
          <el-input v-model="currentAdminData.mail" placeholder="请输入管理员邮箱" clear></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="currentAdminData.password" placeholder="请输入密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="超级管理员权限">
          <span style="margin-left: 1rem;">{{ currentAdminData.super ? '开启' : '关闭' }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogShowStatus.editAdmin = false">取消</el-button>
          <el-button type="primary" @click="submitAdmin(); dialogShowStatus.editAdmin = false;">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { Edit, Delete } from '@element-plus/icons-vue';
import { ref, onMounted, reactive, getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()
import { ElNotification, ElMessageBox } from 'element-plus'
import { getData, currentDataChange } from '../utils/GeneralTool' // 导入全局工具
import router from '@/router';

// --管理员数据获取--
let adminData = ref([]) // 管理员数据
let loginAdminData = reactive({}) // 当前登录的管理员的数据
let tableShow = ref(false)
onMounted(() => {
  // 获取管理员数据
  proxy.$api.getAllAdminData()
    .then(res => {
      getData(res, adminData)
    })
  // 获取当前登录的管理员数据
  proxy.$api.getCurrentAdminData()
    .then(res => {
      loginAdminData = res
      tableShow.value = true
    })
})
let dialogShowStatus = reactive({ // dialog对话框的显示隐藏状态量
  addAdmin: false,
  editAdmin: false,
})

// --添加管理员--
let adminAddData = reactive({}) // 输入数据载体
const addAdminFormRef = ref() // 表单ref对象
const validatePass = (rule, value, callback) => { // 自定义表单验证规则：密码规则
  if (value === '' || value === null) {
    callback(new Error('请输入密码'))
  } else {
    if (adminAddData.passwordAgain !== '') {
      if (!addAdminFormRef.value) return
      addAdminFormRef.value.validateField('checkPass', () => null)
    }
    callback()
  }
}
const validatePass2 = (rule, value, callback) => { // 自定义表单验证规则：再次输入密码规则
  if (value === '' || value === null) {
    callback(new Error('请再次输入该密码'))
  } else if (value !== adminAddData.password) {
    callback(new Error("两次输入的密码不一致"))
  } else {
    callback()
  }
}
const validateMail = (rule, value, callback) => { // 自定义表单验证规则：邮箱格式规则
  if (value === '' || value === null) {
    callback(new Error('请输入邮箱'))
  } else {
    const reg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
    if (reg.test(value)) {
      callback();
    } else {
      return callback(new Error("请输入正确的邮箱格式"));
    }
  }
}
const formRuleAddAdmin = reactive({ // 表单规则
  name: [{ required: true, message: '请输入管理员姓名', trigger: 'blur' }],
  mail: [{ required: true, validator: validateMail, trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', validator: validatePass, trigger: 'blur' }],
  passwordAgain: [{ required: true, validator: validatePass2, trigger: 'blur' }],
})
const addAdmin = async () => { // 提交增加管理员事件
  await addAdminFormRef.value.validate((valid) => { // 表单检验
    if (valid) { // 表单规则校验通过
      const data = {
        name: adminAddData.name,
        mail: adminAddData.mail,
        password: adminAddData.password,
        passwordAgain: adminAddData.passwordAgain,
        super: adminAddData.super ? 1 : 0,
      }
      proxy.$api.addAdmin(data)
        .then(res => {
          if (res.affectedRows) {
            data.id = res.insertId
            adminData.value.push(data)
            ElNotification({
              title: '提交成功',
              type: 'success'
            })
          } else {
            ElNotification({
              title: '提交失败，数据库存入失败',
              type: 'error'
            })
          }
        })
    } else { // 规则不通过
      ElNotification({
        title: '提交失败，请完善管理员信息',
        type: 'error'
      })
    }
  })
}

// --编辑管理员--
let currentAdminData = reactive({}) // 当前选中管理员对象
const formRuleEditAdmin = reactive({ // 编辑管理员表单规则
  name: [{ required: true, message: '请输入管理员姓名', trigger: 'blur' }],
  mail: [{ required: true, validator: validateMail, trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
})
const editAdminFormRef = ref()
const submitAdmin = async () => { // 提交编辑管理员事件
  await editAdminFormRef.value.validate((valid) => { // 表单检验
    if (valid) { // 表单规则校验通过
      proxy.$api.updateAdmin(currentAdminData)
        .then(res => {
          if (res.affectedRows) {
            ElNotification({
              title: '提交成功',
              type: 'success'
            })
            router.go(0)
          } else {
            ElNotification({
              title: '提交失败，数据库存入失败',
              type: 'error'
            })
          }
        })
    } else {
      ElNotification({
        title: '提交失败，请完善管理员信息',
        type: 'error'
      })
    }
  })
}

// --删除管理员--
const deleteAdmin = () => {
  ElMessageBox.confirm(
    '是否删除该管理员？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    proxy.$api.deleteAdmin([currentAdminData.id])
      .then(res => {
        if (res.affectedRows) {
          ElNotification({
            title: '删除成功',
            type: 'success'
          })
          router.go(0)
        } else {
          ElNotification({
            title: '删除失败，数据库存入失败！',
            type: 'error'
          })
        }
      })
  }).catch(() => { })
}
</script>

<style lang="scss" scoped>
#addAdmin {
  margin: 0 auto;
  display: block;
  margin-top: 2rem;
  width: 50%;
  height: 5rem;
  font-size: 3rem;
}

#addAdmin:hover {
  background-color: #cccbcbea;
  border: black;
  color: #60626c;
}
</style>
<style scoped>
::v-deep .el-table--scrollable-y .el-table__body-wrapper {
  overflow-y: hidden;
}
</style>